//
//  TPUserInfoViewController.m
//  Tripvi
//
//  Created by xiaowuxiaowu on 2017/6/15.
//  Copyright © 2017年 xiaowuxiaowu. All rights reserved.
//

#import "TPUserInfoViewController.h"
#import "TPUserInfoCell.h"
#import "DatePickerActionSheet.h"
#import "CityPickerActionSheet.h"
#import "ChooseActionSheet.h"
#import "ChoosePhotoAlbum.h"
#import "UITableView+TP.h"
#import "TPUpdateTelViewController.h"
@interface TPUserInfoViewController ()<TPUserInfoCellDelegate,UITextFieldDelegate>
@property (nonatomic,copy)NSArray *titleArray;
@property (nonatomic,strong)ChoosePhotoAlbum *album;
@property (nonatomic,strong)ChooseActionSheet *sheet;
@property (nonatomic,strong)CityPickerActionSheet *citySheet;
@property (nonatomic,strong)DatePickerActionSheet *dateSheet;
@property (nonatomic,strong)LoginModel *loginModel;

@property (nonatomic,strong)UIImage *headerImage;
@end

@implementation TPUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.title = @"我的资料";
    [self setup];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}
-(void)setup{
    
    
//    self.headerImage = Tripvi_avtor;
    self.tableViewStyle = UITableViewStyleGrouped;
    self.tableView.rowHeight = 56.0f;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    _titleArray = [@"头像 昵称 姓名 性别 手机号" componentsSeparatedByString:@" "];
    @weakify(self);
    [self.tableView tp_addFooterWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 160.0f) buttonHeight:38.0 title:@"保存" toBlock:^(NSInteger tag, UIButton *button) {
        @strongify(self);
        [self leftBtnAction:nil];
    }];
    [self updateTitleArray];
   
  
}

-(void)updateTitleArray{
   
    
    self.loginModel = [[LoginModel alloc]init];
    [self.loginModel getLoginModel];
    [self reloadTableView];
}

-(void)updateLocalLoginModel{
    
    
    [[LoginModel shareLoginModel]save];
}

-(void)reloadTableView{
  
        [self.dataSource removeAllObjects];
        
        NSArray *array1 = @[xw_getNULLString(self.loginModel.head),xw_getNULLString(self.loginModel.alias),xw_getNULLString(self.loginModel.user_name),xw_getNULLString([self  geSex]),xw_getNULLString(self.loginModel.mobile)];
        
        [self.dataSource addObjectsFromArray:array1];
        [self.tableView reloadData];
    
   
    
}
-(NSString *)geSex{
  
    return self.loginModel.sex;//self.loginModel.sex == LoginSexTypeGirl ? @"女" : @"男";
}



#pragma mark---tableView

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1.0f;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TPUserInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TPUserInfoCell"];
    if(!cell){
        cell = [[TPUserInfoCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"TPUserInfoCell"];
        
    }
    
    cell.textLabel.text = self.titleArray[indexPath.row];
    cell.textField.tag = indexPath.row;
    cell.textField.text = self.dataSource[indexPath.row];
    cell.textField.delegate = self;
    cell.model = self.loginModel;
    cell.delegate = self;
    
    if(self.headerImage)
        [cell.image_view ym_setImageWithURL:nil placeholderImage:Tripvi_avtor];
    else
    [cell.image_view ym_setImageWithURL:xw_getNULLString(self.dataSource[indexPath.row]) placeholderImage:Tripvi_avtor];
     cell.indexPath = indexPath;
    
    cell.textField.hidden = indexPath.row == 0;
//    cell.accessoryType = indexPath.row == 4 ? UITableViewCellAccessoryNone: UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    
    if(textField.text.length > 0 ){
        
        [self getUpInfoKey:textField.tag == 1 ?@"alias" :@"user_name"  value:textField.text];
        
        if(textField.tag == 1)
            self.loginModel.alias=textField.text;
        else
            self.loginModel.user_name=textField.text;
    }
    return YES;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
  
}
-(void)tpUserInfoCellWithButton:(UIButton *)sender withSwit:(UISwitch *)swith indexPath:(NSIndexPath *)indexPath{
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
//    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    @weakify(self);
    switch (indexPath.section) {
        case 0:{
         
            switch (indexPath.row) {
                case 0:
                {
                    if(self.album)
                        self.album = nil;
                    
                    self.album = [ChoosePhotoAlbum shareSingeWithViewController:self];
                    self.album.isEditedImage = YES;
                    
                    [self showChooseActionSheetBlock:^(NSInteger row) {
                         @strongify(self);
                        if(row  == 0){
                           [self.album takePhoto:^(UIImage *image, id asset, UIImagePickerController *picker, NSDictionary *info) {
                               [self upLoadImage:image];
                           }];
                        }else{
                            [self.album localPhoto:^(UIImage *image, id asset, UIImagePickerController *picker, NSDictionary *info) {
                                 [self upLoadImage:image];
                            }];
                        }
                    } array:@[@"相机",@"从相册选择"]];
                   
                }
                    break;
                    
                case 1:{ //昵称
                  
                 
                }
                    break;
                case 3:{ //性别
                    
                     [self showChooseActionSheetBlock:^(NSInteger row) {
                          @strongify(self);
                         self.loginModel.sex = row == 0 ? @"男":@"女";//LoginSexTypeBoy : LoginSexTypeGirl;
                         
                         [self getUpInfoKey:@"sex" value:@(++row)];
                         
                         
                     } array:@[@"男",@"女"]];
                    
                }
                    break;
                case 4:{
                    
                    TPUpdateTelViewController *userInfoVC = [TPUpdateTelViewController new];
                    [self.navigationController pushViewController:userInfoVC animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
            
        
        }
            break;
            
        default:
            break;
    }
}

-(void)upLoadImage:(UIImage *)image{

    self.headerImage = image;
    
     BaseCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell.image_view tp_startAnimating];
    [[TPPutDataRequest sharePutDataRequest]putData:UIImageJPEGRepresentation(image, 0.1) key:nil complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        DLog(@"info.error------%@",info.error);
        if(!info.error){
            [[TPRequestClient sharedClient]getupdInfoTouristEditKey:@"head" value:key success:^(NSURLSessionDataTask *task, id responseObject, Responese *respone) {
                
                self.loginModel.head =  key;//[TPPutDataRequest getUrl:key];
                [self reloadTableView];
                [cell.image_view tp_stopAnimating];
                [LoginModel shareLoginModel].head = self.loginModel.head;
                [self updateLocalLoginModel];
                
            } failure:^(NSURLSessionDataTask *task, NSError *error, Responese *respone) {
                 [UIView xw_hideTitle:respone.message];
                [cell.image_view tp_stopAnimating];
            } nonetWork:^(NSURLSessionDataTask *task, NSError *error) {
                [cell.image_view tp_stopAnimating];
            }];
        }else{
            [UIView xw_hideTitle:@"CDN Server Error"];
            [cell.image_view tp_stopAnimating];
        }
        
    }];
}

-(void)getUpInfoKey:(NSString *)key value:(id )value{
  
    
        [self reloadTableView];
    
        [[TPRequestClient sharedClient]getupdInfoTouristEditKey:key value:value success:^(NSURLSessionDataTask *task, id responseObject, Responese *respone) {
            
           if([key isEqualToString:@"user_name"])
               [LoginModel shareLoginModel].user_name = value;
            else if ([key isEqualToString:@"alias"])
                [LoginModel shareLoginModel].alias = value;
            else if([key isEqualToString:@"sex"])
                [LoginModel shareLoginModel].sex = self.loginModel.sex;
            else
            [[LoginModel shareLoginModel]setValue:value forKey:key];
            [self updateLocalLoginModel];
                
            } failure:^(NSURLSessionDataTask *task, NSError *error, Responese *respone) {
                [UIView xw_hideTitle:respone.message];
                
            } nonetWork:^(NSURLSessionDataTask *task, NSError *error) {
                
        }];
    
        

}

-(void)showChooseActionSheetBlock:(void(^)(NSInteger row))block array:(NSArray *)array{
    
    _sheet = nil;
    _sheet = [[ChooseActionSheet alloc]init];
    [_sheet showChooseActionSheetBlock:^(NSInteger buttonIndex, BOOL isCannel) {
        
        if(isCannel)
            return ;
        
        block(buttonIndex);
       
        
    } cancelButtonTitle:@"取消" array:array];
}




@end
